package com.graden.background.service.systoken.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graden.background.repository.systoken.SysTokenMapper;
import com.graden.background.repository.systoken.entity.SysToken;
import com.graden.background.service.systoken.ISysTokenService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * token 服务实现类
 * </p>
 *
 * @author zjf
 * @since 2019-03-25
 */
@Service
public class SysTokenServiceImpl extends ServiceImpl<SysTokenMapper, SysToken> implements ISysTokenService {

	@Override
	public void save(String token, String bipCode) {
		SysToken sysTokenResult = this.getOneByBipCode(bipCode);

		SysToken sysToken = new SysToken();
		sysToken.setToken(token);
		sysToken.setBipCode(bipCode);
		sysToken.setRefreshTime(LocalDateTime.now());
		sysToken.setUpdateTime(LocalDateTime.now());
		sysToken.setStatus(true);

		if(sysTokenResult == null){
			sysToken.setCreateTime(LocalDateTime.now());
			this.save(sysToken);
		}else{
			QueryWrapper<SysToken> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("bip_code",bipCode);
			this.update(sysToken,queryWrapper);
		}
	}

	/**
	 * bipCode
	 */
	@Override
	public SysToken getOneByBipCode(String bipCode) {
		QueryWrapper<SysToken> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("bip_code", bipCode);
		queryWrapper.eq("status", true);

		return this.getOne(queryWrapper);
	}

	/**
	 * 根据token取信息
	 */
	@Override
	public SysToken getOneByToken(String token) {
		QueryWrapper<SysToken> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("token", token);
		queryWrapper.eq("status", true);

		return this.getOne(queryWrapper);
	}

	/**
	 * token刷新时间
	 */
	@Override
	public void tokenRefresh(String token) {
		UpdateWrapper<SysToken> updateWrapper = new UpdateWrapper();
		updateWrapper.set("refresh_time", LocalDateTime.now());
		updateWrapper.eq("token", token);
		this.update(updateWrapper);
	}


}
